package fun.tan90.easy.binlog.plugin.kafka.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import fun.tan90.easy.binlog.base.enums.OutputTypeEnum;
import fun.tan90.easy.binlog.plugin.common.listener.CaffeineRemovalListener;
import fun.tan90.easy.binlog.plugin.kafka.listener.KafkaEventProcessor;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.springframework.context.annotation.Bean;

import java.util.concurrent.TimeUnit;

/**
 * description
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2022/07/13 13:02
 */
@Slf4j
public class KafkaPluginAutoConfiguration {


    public KafkaPluginAutoConfiguration() {
        log.info("init KafkaPlugin");
    }

    @Bean
    public KafkaClientCacheLoader kafkaClientCacheLoader() {
        return new KafkaClientCacheLoader();
    }

    @Bean
    public LoadingCache<String, KafkaProducer<String, String>> kafkaProducerCache(KafkaClientCacheLoader kafkaClientCacheLoader) {
        return Caffeine.newBuilder()
                .maximumSize(10_000)
                .removalListener(new CaffeineRemovalListener(OutputTypeEnum.KAFKA.getOutput()))
                .expireAfterAccess(1, TimeUnit.DAYS)
                .build(kafkaClientCacheLoader);
    }

    @Bean
    public KafkaEventProcessor kafkaEventProcessor(LoadingCache<String, KafkaProducer<String, String>> kafkaProducerCache) {
        return new KafkaEventProcessor(kafkaProducerCache);
    }
}
